<?php
include_once('./simple_html_dom.php');

// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("otafood") or die(mysql_error());

// Get the http GET parameters
$id = $_GET["id"];
$name = $_GET["name"];
$rate = $_GET["rate"];
$food = $_GET["food"];
$restaurant = $_GET["restaurant"];

// $id = 'CM/YQ1blmhtvbC9myAJasQ==';
// $name = 'rTb6x06vxwRIu2z7V2uyxw==';
$key = 'You can never guess me';

$td = mcrypt_module_open ('des', '', 'ecb', ''); 
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND); 
mcrypt_generic_init ($td, $key, $iv); 
$decodedId = base64_decode($id);
$id_decrypt = mdecrypt_generic ($td, $decodedId); 

mcrypt_generic_init ($td, $key, $iv); 
$decodedName = base64_decode($name);
$name_decrypt = mdecrypt_generic ($td, $decodedName); 

$trimmed = preg_replace('/[^(\x20-\x7F)]*/','', $id_decrypt);
$response = file_get_contents("http://graph.facebook.com/". $trimmed . "?fields=name");
$arr = json_decode($response);
$name_facebook = preg_replace('/[^(\x20-\x7F)]*/','', $arr->{"name"});

if($name_facebook === preg_replace('/[^(\x20-\x7F)]*/','', $name_decrypt)){
	
	// Formulate the query to get the current rate
	$query = sprintf("SELECT rating, nu_rating FROM foodlist WHERE food='%s' AND restaurant='%s'",
		mysql_real_escape_string($food),
		mysql_real_escape_string($restaurant));
    	
	// Perform Query
	$result = mysql_query($query);
	
	// Get the result in a variable
	$row = mysql_fetch_assoc($result);
	
	// Calculate the new rate
	$new_rate = (($row["rating"] * $row["nu_rating"]) + $rate) / ($row["nu_rate"] + 1);
	
	// Formulate the query to update the rate to new rate
	$query = sprintf("UPDATE foodlist SET rate='%s' WHERE food='%s' AND restaurant='%s'",
		mysql_real_escape_string($new_rate),
		mysql_real_escape_string($food),
		mysql_real_escape_string($restaurant));
		
	// Perform Query
	$result = mysql_query($query);	
}

?>
